﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CFM.API;
using CFM.DTO;
using CFM.Common;
using System.Text.RegularExpressions;

namespace CFM
{
    public partial class frmInputNew : Form
    {
        private ProductAPI _apiProduct = null;
        private ProviderAPI _apiProvider = null;
        private CategoriesAPI _apiCate = null;
        private ImportAPI _apiImport = null;
        private List<ImportDetail> lsImprotDetail = null;
        private List<Provider> lsProvider = null;
        private List<Categories> lsCate = null;
        private List<Product> lsProduct = null;
        public frmInputNew()
        {
            InitializeComponent();
            _apiProduct = new ProductAPI();
            _apiProvider = new ProviderAPI();
            _apiCate = new CategoriesAPI();
            _apiImport = new ImportAPI();
            lsImprotDetail = new List<ImportDetail>();
            lsProvider = new List<Provider>();
            lsCate = new List<Categories>();
            lsProduct = new List<Product>();
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void frmInputNew_Load(object sender, EventArgs e)
        {
            grvImportDetail.AutoGenerateColumns = false;
            grvImportDetail.DataSource = lsImprotDetail;

            List<Provider> providers = new List<Provider>();
            providers.Add(new Provider() { ProviderId = "-1", ProviderName = "-- chọn nhà cung cấp --" });
            providers.AddRange(_apiProvider.GetAll());            
            cbxProvider.DataSource = providers;
            cbxProvider.DisplayMember = "ProviderName";
            cbxProvider.ValueMember = "ProviderId";
            cbxProvider.SelectedValue = "-1";  

            List<Categories> cates = new List<Categories>();
            cates.Add(new Categories() { CategoryId = "-1", CategoryName = "- chọn nhóm sản phẩm --" });
            cates.AddRange(_apiCate.GetAll());
            cbxCategory.DataSource = cates;
            cbxCategory.ValueMember = "CategoryId";
            cbxCategory.DisplayMember = "CategoryName";
            cbxCategory.SelectedValue = "-1";

            List<Product> products = new List<Product>();
            products.Add(new Product() { ProductId = "-1", ProductName = "-- chọn sản phẩm --" });
            cbxProduct.DataSource = products;
            cbxProduct.DisplayMember = "ProductName";
            cbxProduct.ValueMember = "ProductId";
            cbxProduct.SelectedValue = "-1";
                                              
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            cbxProvider.SelectedValue = "-1";  
            cbxCategory.SelectedValue = "-1";
            cbxProduct.SelectedValue = "-1";
            txtQuantity.Text = string.Empty;
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            bool flag = true;
            if (cbxProduct.Enabled && cbxProduct.SelectedValue.ToString() == "-1")
            {
                MethodHelper.AddErrorProvider(cbxProduct, Const.EMPTY_MESSAGE);
                flag = false;
            }            
            if (txtQuantity.Enabled && txtQuantity.Text.Trim().Length == 0)
            {
                MethodHelper.AddErrorProvider(txtQuantity, Const.EMPTY_MESSAGE);
                flag = false;
            }
            if (!flag)
                return;
            ImportDetail importDetail = new ImportDetail();
            var temp = lsImprotDetail.Where(r => r.ProductId.Trim() == cbxProduct.SelectedValue.ToString().Trim()).ToList();
            if (temp.Count > 0)
            {
                importDetail = temp.FirstOrDefault();            
                importDetail.Quantity += Convert.ToInt32(txtQuantity.Text.Trim());
                double quantity = (double)(importDetail.Quantity);
                double price = (double)(importDetail.Price);
                double totaldetail = quantity * price;
                importDetail.DetailTotal = totaldetail;
            }
            else
            {
                Product product = new Product();
                product = _apiProduct.GetProductByProductId(cbxProduct.SelectedValue.ToString());
                importDetail.ProductId = product.ProductId.Trim();
                importDetail.ProductName = product.ProductName;
                importDetail.ProductId = product.ProductId;
                importDetail.UnitId = product.Unit2Id;
                importDetail.Price = product.BuyPrice;
                importDetail.Quantity = Convert.ToInt32(txtQuantity.Text.Trim());
                importDetail.CategoryId = cbxCategory.SelectedValue.ToString();
                float quantity = (float)(importDetail.Quantity);
                float price = (float)(importDetail.Price);
                float totaldetail = quantity * price;
                importDetail.DetailTotal = totaldetail;
                lsImprotDetail.Add(importDetail);
            }
            double total = lsImprotDetail.Sum(r => r.DetailTotal);
            txtTotal.Text = total.ToString();
            grvImportDetail.DataSource = null;
            grvImportDetail.DataSource = lsImprotDetail.ToList();
            MethodHelper.ClearErrorProvider();
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
           
               
            ImportDetail imp = new ImportDetail();
            imp.ProductId = cbxProduct.SelectedValue.ToString();
            txtQuantity.Focus();
            imp = lsImprotDetail.Where(r => r.ProductId.Trim() == imp.ProductId.Trim()).First();
            imp.Quantity = Convert.ToInt32(txtQuantity.Text);
            float quantity = (float)(imp.Quantity);
            float price = (float)(imp.Price);
            float totaldetail = quantity * price;
            imp.DetailTotal = totaldetail;
            double total = lsImprotDetail.Sum(r => r.DetailTotal);
            txtTotal.Text = total.ToString();
            grvImportDetail.DataSource = lsImprotDetail.ToList();
        }

        private void cbxCategory_SelectedIndexChanged(object sender, EventArgs e)
        {
            string cateid = cbxCategory.SelectedValue.ToString();            
            List<Product> products = new List<Product>();
            products.Add(new Product() { ProductId = "-1", ProductName = "-- chọn sản phẩm --" });
            products.AddRange(_apiProduct.GetProByCateId(cateid));
            cbxProduct.DataSource = products;
            cbxProduct.DisplayMember = "ProductName";
            cbxProduct.ValueMember = "ProductId";
            cbxProduct.SelectedValue = "-1";
            MethodHelper.ClearErrorProvider();
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {

            ImportDetail imp = new ImportDetail();
            imp.ProductId = cbxProduct.SelectedValue.ToString();
            var details = lsImprotDetail.Where(r => r.ProductId.Trim() == imp.ProductId.Trim());
            if (details.ToList().Count() > 0)
            {
                imp = details.First();
                lsImprotDetail.Remove(imp);
                grvImportDetail.DataSource = lsImprotDetail.ToList();
            }
        }

        private void grvImportDetail_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0)
                return;
            ImportDetail imp = grvImportDetail.Rows[e.RowIndex].DataBoundItem as ImportDetail;
            txtQuantity.Text = imp.Quantity.ToString();
            cbxCategory.SelectedValue = imp.CategoryId;
            cbxProduct.SelectedValue = imp.ProductId.Trim();
            MethodHelper.ClearErrorProvider();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (cbxProvider.Enabled && cbxProvider.SelectedValue.ToString() == "-1")
            {
                MethodHelper.AddErrorProvider(cbxProvider, Const.EMPTY_MESSAGE);
                return;
            }
            MethodHelper.ClearErrorProvider();
            Import impt = new Import();
            impt.ImportId = MethodHelper.GetInputId();
            impt.ProviderId = cbxProvider.SelectedValue.ToString();
            impt.ProviderName = cbxProvider.Text;
            impt.Total = Convert.ToInt32(txtTotal.Text.ToString());
            impt.UserId = "Admin";
            impt.ImportDate = DateTime.Now;
            bool result = _apiImport.CreateImport(impt);
            if (result == true)
            {
                ImportDetail imptdt = new ImportDetail();
                string imtID = impt.ImportId;
                bool rs = true;
                foreach (var im in lsImprotDetail)
                {
                    imptdt.ImportId = imtID;
                    imptdt.ProductId = im.ProductId;
                    imptdt.ProductName = im.ProductName;
                    imptdt.UnitId = im.UnitId;
                    imptdt.Quantity = im.Quantity;
                    imptdt.DetailTotal = im.DetailTotal;
                    imptdt.Price = im.Price;
                    rs= _apiImport.CreateImportDetail(imptdt);
                    if (rs == false)
                    {
                        break;
                    }
                }
                if (rs)
                {
                    MessageBox.Show("Lưu thành công!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.Close();
                }
                else
                    MessageBox.Show("Lưu không thành công!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error); 
                
            }
            else
            {
                MessageBox.Show("Lưu không thành công!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error); 
            }

        }

        private void txtQuantity_KeyPress(object sender, KeyPressEventArgs e)
        {
            MethodHelper.OnlyNumberIntTextBox(sender as TextBox, e);
        }
    }
}
